/*
	This file is part of the JKTest
    Copyright (C) 2008 Royce Y. Feng <ryfeng@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License version 3
    as published by the Free Software Foundation. You may not use, modify
    or distribute this program under any other version of the
    GNU Affero General Public License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package JKPanels;

import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JFileChooser;

import jktest.JKMainPanel;
import jktest.JKMainGui;
import jktest.JKButton;
import jktest.JMultilineLabel;
import jktest.JKFileFilter;

/**
 * 
 * Panel Class containing all elements of the OpenOffice Test
 * 
 * @author Royce Feng
 */
public class OpenOfficePanel extends JKMainPanel {

    private PassFailPanel passFail;
    
    /**
     * 
     * Main Constructor for OpenOfficePanel. Creates a multiline label with instructions
     * as well as the three main buttons: Start test, Pass, Fail.
     * 
     * @param _parent The Parent Class (for communication)
     */
    public OpenOfficePanel ( JKMainGui _parent ) {
        super(_parent);
        JMultilineLabel instructions = new JMultilineLabel();
        instructions.setMaxWidth(500);
        instructions.setText("After you click the button, JKTest will automatically search for your OpenOffice" +
                " directory. If none are found, the test fails. If JKTest fails to open anything, the test fails" +
                ". Otherwise, it passes.");
        this.add(instructions);
        JKButton button = new JKButton(this,"OpenOffice");
        button.setPreferredSize(new Dimension(200,25));
        this.add( button );
        passFail = new PassFailPanel(this);
        passFail.setPreferredSize(new Dimension(500,25));
        this.add(passFail);
    }
    
    /**
     * 
     * Returns the name of the panel
     * 
     * @return The name of the panel
     */
    @Override
    public String getName() {
        return "OpenOffice";
    }
    
    /**
     * 
     * Helper function. Returns the greatest of an ArrayList of Strings.
     * 
     * @param base The Base ArrayList
     * @return The greatest string of the ArrayList
     */
    private String getHighestRev( ArrayList<String> base ) {
        String comp = "";
        for ( int i = 0; i < base.size(); i++ ) {
            if ( comp.equals("") ) {
                comp = base.get(i);
            } else {
                if ( comp.compareToIgnoreCase(base.get(i)) > 0 ) {
                    comp = base.get(i);
                }
            }
        }
        return comp;
    }

    private boolean runInstallation( String progFilesVar ) {
        String root = "C:";
        if ( (root = System.getenv("HOMEDRIVE") ) != null ) {
            File f = new File(root+"\\"+progFilesVar);
            if ( f.exists() ) {
                String[] children = f.list();
                ArrayList<String> openOfficeDirs = new ArrayList<String>();
                for ( int i = 0; i < children.length; i++ ) {
                    if ( children[i].indexOf("OpenOffice") >= 0 ) {
                        openOfficeDirs.add(children[i]);
                    }
                }
                if (openOfficeDirs.size() != 0) {
                    System.out.println("Hi");
                    String ooLoc = getHighestRev(openOfficeDirs);
                    ooLoc += "\\program\\soffice.exe";
                    ooLoc = "\"" + root + "\\" + progFilesVar + "\\" + ooLoc + "\"";
                    String osName = System.getProperty("os.name");
                    if (osName.toUpperCase().startsWith(("WINDOWS"))) {
                        try {
                            Runtime.getRuntime().exec(ooLoc);
                            return true;
                        } catch (IOException e) {
                            JOptionPane.showMessageDialog(this, "Error running" + ooLoc, "Program Error", JOptionPane.ERROR_MESSAGE);
                            getThisParent().valChanged(this.getName(), false);
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Current Operating System is not windows", "Unrecognized Operating System", JOptionPane.ERROR_MESSAGE);
                    }
                    
                }
            }
        }
        return false;
    }
    
    /**
     * 
     * Handles button clicks. Pass/fail gets sent to parent while the test is run
     * when the test button is clicked.
     * 
     * @param source Button source (usually the button text)
     */
    public void ButtonClicked( String source ) {
        if ( source.equals("Pass") ) {
            getThisParent().valChanged(this.getName(), true);
            getThisParent().incPanel();
        } else if ( source.equals("Fail") ) {
            getThisParent().valChanged(this.getName(), false);
            getThisParent().incPanel();
        } else {
            if ( !runInstallation("Program Files") ) {
                JOptionPane.showMessageDialog(this,"Could not find OpenOffice.org in Program Files, now trying Program Files (x86)","Warning",JOptionPane.WARNING_MESSAGE);
                if ( !runInstallation("Program Files (x86)") ) {
                    JOptionPane.showMessageDialog(this,"Could not find OpenOffice.org in Program Files (x86)","Warning",JOptionPane.WARNING_MESSAGE);
                    int confirmation = JOptionPane.showConfirmDialog(null,"Do you want to search for swriter.exe?",
                        "Confirmation",JOptionPane.YES_NO_OPTION);
                    if ( confirmation == JOptionPane.YES_OPTION ) {
                        String sysRoot;
                        JFileChooser chooser;
                        if ( ( sysRoot = System.getenv("HOMEDRIVE") ) != null )
                            chooser = new JFileChooser(sysRoot);
                        else
                            chooser = new JFileChooser();
                        JKFileFilter exeFilter = new JKFileFilter("swriter.exe", new String[] { "EXE" });
                        chooser.addChoosableFileFilter(exeFilter);
                        int result = chooser.showOpenDialog(this);
                        switch ( result ) {
                            case JFileChooser.APPROVE_OPTION:
                                String osName = System.getProperty("os.name");
                                if (osName.toUpperCase().startsWith(("WINDOWS"))) {
                                    try {
                                        Runtime.getRuntime().exec(chooser.getSelectedFile().toString());
                                        getThisParent().valChanged(this.getName(), true);
                                    } catch (IOException e) {
                                        JOptionPane.showMessageDialog(this, "Error running" + chooser.getSelectedFile(), "Program Error", JOptionPane.ERROR_MESSAGE);
                                        getThisParent().valChanged(this.getName(), false);
                                    }
                                } else {
                                    JOptionPane.showMessageDialog(this, "Current Operating System is not windows", "Unrecognized Operating System", JOptionPane.ERROR_MESSAGE);
                                }
                                break;
                            case JFileChooser.CANCEL_OPTION:
                                break;
                            case JFileChooser.ERROR_OPTION:
                                JOptionPane.showMessageDialog(this, "Error with file chosen", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        getThisParent().valChanged(this.getName(), false);
                    }
                } else {
                    getThisParent().valChanged(this.getName(), true);
                }
            } else {
                getThisParent().valChanged(this.getName(), true);
            }
        }
    }
    
}
